package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// Transaction 交易记录模型
type Transaction struct {
	BaseModel
	TransactionNo  string  `orm:"size(64);unique" json:"transaction_no"` // 交易流水号
	OrderNo        string  `orm:"size(64);index" json:"order_no"`        // 关联订单号
	MemberId       int64   `orm:"index" json:"member_id"`                // 会员ID
	Amount         float64 `orm:"digits(10);decimals(2)" json:"amount"`  // 交易金额
	PaymentChannel string  `orm:"size(20)" json:"payment_channel"`       // 支付渠道：alipay, wechat, balance, etc.
	ChannelTradeNo string  `orm:"size(64)" json:"channel_trade_no"`      // 渠道交易号
	Type           int8    `orm:"default(1)" json:"type"`                // 交易类型：1:支付, 2:退款, 3:充值, 4:提现
	Status         int8    `orm:"default(0)" json:"status"`              // 交易状态：0:处理中, 1:成功, 2:失败
	CompletionTime int64   `orm:"default(0)" json:"completion_time"`     // 交易完成时间
	Remark         string  `orm:"size(255)" json:"remark"`               // 备注
	RawData        string  `orm:"type(text)" json:"raw_data"`            // 原始交易数据（JSON格式）
}

// TableName 设置表名
func (t *Transaction) TableName() string {
	return "ss_transaction"
}

// GetTransactionById 根据ID获取交易记录，带加盟商权限验证
func GetTransactionById(id int64, franchiseId int64) (*Transaction, error) {
	o := orm.NewOrm()
	transaction := &Transaction{BaseModel: BaseModel{Id: id}}
	err := o.Read(transaction)
	if err != nil {
		return nil, err
	}

	// 加盟商权限验证
	if franchiseId > 0 {
		// 验证会员是否属于该加盟商
		member := &Member{BaseModel: BaseModel{Id: transaction.MemberId}}
		err = o.Read(member)
		if err != nil {
			return nil, err
		}

		if member.FranchiseId != franchiseId {
			return nil, orm.ErrNoRows
		}
	}

	return transaction, nil
}

// GetTransactionByTransactionNo 根据交易流水号获取交易记录
func GetTransactionByTransactionNo(transactionNo string) (*Transaction, error) {
	transaction := &Transaction{TransactionNo: transactionNo}
	o := orm.NewOrm()
	err := o.Read(transaction, "TransactionNo")
	return transaction, err
}

// GetTransactionList 获取交易记录列表
func GetTransactionList(page, pageSize int, filters map[string]interface{}) ([]*Transaction, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Transaction))

	// 应用过滤条件
	if transactionNo, ok := filters["transaction_no"].(string); ok && transactionNo != "" {
		qs = qs.Filter("transaction_no", transactionNo)
	}

	if orderNo, ok := filters["order_no"].(string); ok && orderNo != "" {
		qs = qs.Filter("order_no", orderNo)
	}

	if memberId, ok := filters["member_id"].(int64); ok {
		qs = qs.Filter("member_id", memberId)
	}

	if paymentChannel, ok := filters["payment_channel"].(string); ok && paymentChannel != "" {
		qs = qs.Filter("payment_channel", paymentChannel)
	}

	if transactionType, ok := filters["type"].(int8); ok {
		qs = qs.Filter("type", transactionType)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	// 时间范围过滤
	if startTime, ok := filters["start_time"].(int64); ok {
		qs = qs.Filter("created_at__gte", startTime)
	}

	if endTime, ok := filters["end_time"].(int64); ok {
		qs = qs.Filter("created_at__lte", endTime)
	}

	// 加盟商权限过滤
	if franchiseId, ok := filters["franchise_id"].(int64); ok && franchiseId > 0 {
		// 获取该加盟商下的所有会员ID
		var memberIds orm.ParamsList
		_, err := o.QueryTable(new(Member)).
			Filter("franchise_id", franchiseId).
			Filter("is_deleted", 0).
			ValuesFlat(&memberIds, "id")
		if err != nil {
			return nil, 0, err
		}
		if len(memberIds) > 0 {
			qs = qs.Filter("member_id__in", memberIds)
		} else {
			// 如果没有会员，直接返回空列表
			return []*Transaction{}, 0, nil
		}
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var transactions []*Transaction
	_, err := qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&transactions)

	return transactions, total, err
}

// CreateTransaction 创建交易记录
func CreateTransaction(transaction *Transaction) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(transaction)
	return id, err
}

// UpdateTransaction 更新交易记录
func UpdateTransaction(transaction *Transaction, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(transaction, fields...)
	return err
}

// UpdateTransactionStatus 更新交易状态
func UpdateTransactionStatus(id int64, status int8, channelTradeNo string) error {
	o := orm.NewOrm()
	transaction := &Transaction{BaseModel: BaseModel{Id: id}}
	if err := o.Read(transaction); err != nil {
		return err
	}

	transaction.Status = status
	transaction.ChannelTradeNo = channelTradeNo

	if status == 1 { // 成功
		transaction.CompletionTime = time.Now().Unix()
	}

	_, err := o.Update(transaction, "Status", "ChannelTradeNo", "CompletionTime", "UpdatedAt")
	return err
}

// GetMemberTransactions 获取会员的交易记录
func GetMemberTransactions(memberId int64, page, pageSize int) ([]*Transaction, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Transaction)).Filter("member_id", memberId).Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var transactions []*Transaction
	_, err := qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&transactions)

	return transactions, total, err
}
